package org.adorsys.aderp.orga.service;

import java.util.List;

import org.adorsys.aderp.orga.domain.EmailAddressRole;
import org.adorsys.aderp.orga.domain.OrgaPerson;
import org.adorsys.aderp.orga.domain.OrgaResource;
import org.adorsys.aderp.orga.domain.PersonEmail;
import org.adorsys.aderp.orga.domain.ResourceEmail;
import org.adorsys.aderp.orga.repository.ResourceEmailRepository;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;


public class ResourceEmailServiceImpl implements ResourceEmailService {
	
		   
	@Override
	public List<ResourceEmail> findByOrgaResource(OrgaResource orgaResource) {
		return resourceEmailRepository.findByOrgaResource(orgaResource);
	}
	
    public void saveResourceEmail(ResourceEmail resourceEmail) {
    	OrgaResource orgaResource = resourceEmail.getOrgaResource();
    	if(StringUtils.isBlank(resourceEmail.getResourceAddressKey())){
    		 EmailAddressRole addressRole = resourceEmail.getAddressRole();
    		 resourceEmail.setResourceAddressKey(orgaResource.getResourceKey() +":"+addressRole.getAddressRoleKey() +":"+RandomStringUtils.randomNumeric(3));
    	}
    	// this is a dependent object of the orgaResource. So same record owner.
    	if(StringUtils.isBlank(resourceEmail.getRecordOwner())){
    		resourceEmail.setRecordOwner(orgaResource.getRecordOwner());
    	}
    	resourceEmailRepository.save(resourceEmail);
    }
    
    @Override
    public Page<ResourceEmail> searchResourceEmail(OrgaResource orgaResource,EmailAddressRole addressRole, Integer page, Integer size) {
		PageRequest pageable = new PageRequest(page, size);
		if(orgaResource!=null && addressRole==null){
			return resourceEmailRepository.findByOrgaResource(orgaResource, pageable);
		} else if(orgaResource!=null && addressRole!=null){
			return resourceEmailRepository.findByOrgaResourceAndAddressRole(orgaResource, addressRole, pageable);
		} else if(orgaResource==null && addressRole!=null){
			return resourceEmailRepository.findByAddressRole(addressRole, pageable);
		} else {
			return resourceEmailRepository.findAll(pageable);
		}
    }

}
